﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;
using Utilities;

namespace Sovigaz.DataProvider
{
    public class PermissionAttribute : ActionFilterAttribute
    {
        public string SitemapID { get; set; }

        public int PermissionID { get; set; }

        public string PageType { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var context = new SovigazDbContext();
                var permissions = context.Database.SqlQuery<sp_User_SelectPermission>(
                        "sp_User_SelectPermission @UserID, @SitemapID"
                        , new SqlParameter { ParameterName = "UserID", Value = Utility.UserID }
                        , new SqlParameter { ParameterName = "SitemapID", Value = SitemapID }).ToList();
            bool iuPermission =  permissions.Exists(p => p.PermissionID == 2 && p.IsActived);

            if (Utility.UserID == 1)
            {
                filterContext.Controller.ViewBag.InsertPermission = true;
                filterContext.Controller.ViewBag.UpdatePermission = true && PageType == "List";
                filterContext.Controller.ViewBag.DeletePermission = true;
                filterContext.Controller.ViewBag.BackEnable = PageType == "Detail";
            }
            else
            {
                filterContext.Controller.ViewBag.InsertPermission = iuPermission;
                filterContext.Controller.ViewBag.UpdatePermission = iuPermission && PageType == "List";
                filterContext.Controller.ViewBag.DeletePermission = permissions.Exists(p => p.PermissionID == 3 && p.IsActived);
                filterContext.Controller.ViewBag.BackEnable = PageType == "Detail";
            }

            base.OnActionExecuting(filterContext);
        }
    }
}
